<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTool>
        <template slot="right">
          <el-button type="primary" size="small" @click="$router.push('/import?type=employees')">导入</el-button>
          <el-button type="warning" size="small" @click="exportExcelData">导出</el-button>
          <el-button v-if="checkPermission('POINT-USER-ADD')" type="success" size="small" @click="showDialog = true">+ 新增员工</el-button>
        </template>
      </PageTool>
      <el-card>
        <el-table :data="list">
          <el-table-column label="序号" sortable>
            <template slot-scope="{$index}">{{ pageSetting.size * (pageSetting.page - 1) + 1 + $index }}</template>
          </el-table-column>
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable prop="departmentName" />
          <el-table-column label="入职日期" sortable>
            <template slot-scope="{row}">{{ row.timeOfEntry | formatDate }}</template>
          </el-table-column>
          <el-table-column label="账户状态">
            <template slot-scope="{row}">
              <el-switch :value="row.enableState === 1" inactive-color="#ff4949" />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/' +row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button v-if="checkPermission('point-user-delete')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" align="middle" style="height:100px">
          <el-pagination layout=" prev, pager, next, sizes,total,jumper" :total="pageSetting.total" :page-size="pageSetting.size" :page-sizes="[10,15,20,25,30]" @current-change="currentChange" @size-change="sizeChange" />
        </el-row>
      </el-card>
      <AddEmployee :show-dialog.sync="showDialog" @addEmployee="getEmployees" />
    </div>
  </div>
</template>

<script>
import { getEmployees, delEmployee } from '@/api/employees'
import employmentEnum from '@/api/constant/employees'
import AddEmployee from './components/AddEmployee'
import { formatDate } from '@/filters'
export default {
  components: {
    AddEmployee
  },
  data() {
    return {
      list: [],
      total: 0,
      pageSetting: {
        page: 1,
        size: 10,
        total: 0
      },
      showDialog: false
    }
  },
  created() {
    this.getEmployees()
  },
  methods: {
    async delEmployee(id) {
      try {
        await this.$confirm('员工一旦删除无法恢复,请确认删除')
        await delEmployee(id)
        await this.getEmployees()
        await this.$message.success('成功删除员工!')
      } catch (error) {
        console.dir(error)
      }
    },
    async getEmployees() {
      try {
        const { rows, total } = await getEmployees(this.pageSetting)
        this.list = rows
        this.pageSetting.total = total
      } catch (error) {
        console.dir(error)
      }
    },
    currentChange(newPage) {
      this.pageSetting.page = newPage
      this.getEmployees()
    },
    sizeChange(newSize) {
      this.pageSetting.size = newSize
      this.getEmployees()
    },
    formatEmployment(row, column, cellvalue) {
      const hireObj = employmentEnum.hireType.find(item => item.id === cellvalue)
      // 防御性编程,预防没有找到符合条件的对象
      return hireObj ? hireObj.value : '未知'
    },
    async exportExcelData() {
      try {
        const headerEnum = {
          '姓名': 'username',
          '手机号': 'mobile',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName',
          '入职日期': 'timeOfEntry',
          '转正日期': 'correctionTime'
        }
        const header = Object.keys(headerEnum)

        const { rows } = await getEmployees({
          page: 1,
          size: this.pageSetting.total
        })
        const data = rows.map(item => {
          return this.Obj2Arr(item, headerEnum)
        })

        // js-xlsx体积很大，导出功能也不常用，所以使用的时候懒加载
        const excel = await import('@/vendor/Export2Excel')
        excel.export_json_to_excel({
          header,
          data,
          filename: '员工信息表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      } catch (error) {
        console.dir(error)
      }
    },
    Obj2Arr(item, dictionary) {
      const EmployeesArr = []
      for (const key in dictionary) {
        const enKey = dictionary[key]
        let value = item[enKey]
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // value = value.split('T')[0]
          value = formatDate(value)
        }
        if (enKey === 'formOfEmployment') {
          const hireTypeObj = employmentEnum.hireType.find(item => item.id === value)
          value = hireTypeObj ? hireTypeObj.value : '未知聘用类型'
        }
        EmployeesArr.push(value)
      }
      return EmployeesArr
    }
  }
}
</script>

<style>

</style>
